package kr.shincooper.funnyhome.controller;

import java.util.Map;

import kr.shincooper.funnyhome.common.APIUtil;
import kr.shincooper.funnyhome.model.ResultModel;
import kr.shincooper.funnyhome.service.MemberService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Member들의 정보를 관리하는 API를 컨트롤 하는 클래스.
 * 
 * @author bluemirr5
 *
 */
@Controller
public class MemberController {
	
	@Autowired
	private MemberService memberService;
	
	/**
	 * Member의 정보를 반환한다.
	 * 
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping (
		value="/member/{memberId}",
		method=RequestMethod.GET,
		consumes="application/json"
	)
	public @ResponseBody ResultModel getMemberJson(
			@PathVariable String memberId
			) throws Exception {
		return APIUtil.makeSuccessAPIResult(memberService.getMember(memberId));
	}
	@RequestMapping (
		value="/member/{memberId}",
		method=RequestMethod.GET
	)
	public String getMember(
			@PathVariable String memberId,
			Model model
			) throws Exception {
		model.addAttribute("member", memberService.getMember(memberId));
		return "member";
	}
	
	/**
	 * Member의 모든 사람들의 정보를 반환한다.
	 * 
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping (
		value="/member",
		method=RequestMethod.GET,
		consumes="application/json"
	)
	public @ResponseBody ResultModel getMemberListJson(
			) throws Exception {
		return APIUtil.makeSuccessAPIResult(memberService.getMember());
	}
	@RequestMapping (
		value="/member",
		method=RequestMethod.GET
	)
	public String getMemberList(
			Model model
			) throws Exception {
		model.addAttribute("members", memberService.getMember());
		return "member/memberList";
	}
	
	@RequestMapping (
		value="/login",
		method=RequestMethod.GET
	)
	public String loginPage() throws Exception {
		return "member/login";
	}
			
	/**
	 * Member의 로그인 요청을 받아 확인하여 결과를 반환한다.
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping (
		value="/login",
		method=RequestMethod.POST
	)
	public @ResponseBody ResultModel loginJson(
			@RequestBody Map<String, String> param
			) throws Exception {
		
		System.out.println("id : "+param.get("id") + ", pass : "+ param.get("pass"));
		String token = memberService.login(param.get("id"), param.get("pass"));
		return APIUtil.makeSuccessAPIResult(token);
	}
}
